﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using IESN.DAL;
using System.Reflection;
using System.Text.RegularExpressions;

namespace IESN.BaseForms
{
    /// <summary>
    /// 编辑界面基础窗体，所有操作型界面，继承此窗体
    /// </summary>
    public partial class EditBaseFrm : BaseFrm
    {
        #region 界面变量

        /// <summary>
        /// 当前操作模式 
        /// </summary>
        private OperationModel _currentOperate;
        private OperationModel CurrentOperate
        {
            get { return _currentOperate; }
            set
            {
                _currentOperate = value;
                OnOperationModelChanged();
            }
        }

        /// <summary>
        /// 操作状态改变时触发
        /// </summary>
        private void OnOperationModelChanged()
        {
            switch (CurrentOperate)
            {
                case OperationModel.View:
                    btnAdd.Text = "新增(&A)";
                    btnAdd.Enabled = true;

                    btnEdit.Text = "编辑(&E)";
                    btnEdit.Enabled = true;
                    btnDelete.Enabled = true;
                    btnSave.Enabled = false;
                    panelList.Enabled = true;
                    ControlHelper.SetControlEnable(panelContent, false);
                    break;

                case OperationModel.Add:
                    ControlHelper.SetControlEnable(panelContent, true);
                    panelList.Enabled = false;
                    lblMsg.Visible = true;
                    btnAdd.Text = "取消(&C)";
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                    btnSave.Enabled = true;

                    ControlHelper.ClearControl(panelContent);

                    //设置默认值
                    SetDefaultValue();
                    GetFocus(panelContent);

                    //_sourceObjValueDic.Clear();
                    //CollectFormValue(panelContent, _sourceObjValueDic, _isComboBoxSelectValue);

                    break;

                case OperationModel.Edit:
                    ControlHelper.SetControlEnable(panelContent, true);
                    panelList.Enabled = false;

                    btnEdit.Text = "取消(&C)";
                    GetFocus(panelContent);

                    //_sourceObjValueDic.Clear();
                    //CollectFormValue(panelContent, _sourceObjValueDic, _isComboBoxSelectValue);

                    btnAdd.Enabled = false;
                    btnSave.Enabled = true;
                    btnDelete.Enabled = false;
                    break;
            }
        }

        /// <summary>
        /// 操作的实体类
        /// </summary>
        protected Entity _currentEntity;
        protected Entity CurrentEntity
        {
            get { return _currentEntity; }
            set { _currentEntity = value; }
        }

        //保存界面刚打开时，界面上控件的值
        private Dictionary<string, object> _sourceObjValueDic = new Dictionary<string, object>();

        //界面上控件当前的值
        private Dictionary<string, object> _currentObjValueDic = new Dictionary<string, object>();

        /// <summary>
        /// 取comboBox的值，True:取comboBox的SelectValue值，False:取comboBox的Text值(默认是取text值)
        /// </summary>
        private bool _isComboBoxSelectValue = true;
        protected bool IsComboBoxSelectValue
        {
            get { return _isComboBoxSelectValue; }
            set { _isComboBoxSelectValue = value; }
        }

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        public EditBaseFrm()
        {
            InitializeComponent();
        }

        #endregion
        
        #region 初始化

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditBaseFrm_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                InitForm();
            }
        }

        /// <summary>
        /// 窗体初始化
        /// </summary>
        private void InitForm()
        {
            CurrentOperate = OperationModel.View;

            _appContext.AddFormItem(this.Name,this);
            _controller.AddFormToList(this);

            InitControl();

            GetDataSet();
            SetFormValue();

            //SetDefaultValue();
            //_sourceObjValueDic.Clear();
            //CollectFormValue(panelMain, _sourceObjValueDic, _isComboBoxSelectValue);

            SetOtherControlEnable(IsViewModel());
        }

        /// <summary>
        /// 初始化界面控件
        /// </summary>
        protected virtual void InitControl()
        {
            if (_currentOperate == OperationModel.View)
                ControlHelper.SetControlEnable(panelContent, false);
        }

        #endregion

        #region 可重载方法

        protected DataSet _ds = new DataSet();

        protected virtual DataSet GetDataSet()
        {
            _ds=AccessDBHelper.GetDataSetByTableName(_currentEntity.TableName);

            if (_ds.Tables.Count > 0)
                lblMsg.Text ="共 " +_ds.Tables[0].Rows.Count.ToString()+" 条记录";

            return _ds;
        }

        /// <summary>
        /// 设置窗体中其他控件的是否可编辑状态
        /// </summary>
        /// <param name="isView">true:查看模式  false:非查看模式</param>
        protected virtual void SetOtherControlEnable(bool isView)
        {
        }

        /// <summary>
        /// 设置界面的值
        /// </summary>
        protected virtual void SetFormValue()
        {
            if (panelList.Controls!=null && panelList.Controls.Count>0&& panelList.Controls[0] is DataGridView)
            {
                DataGridView dg = panelList.Controls[0] as DataGridView;

                BindingSource bs = new BindingSource();
                bs.DataSource = _ds.Tables[0];
                dg.DataSource = bs;
            }
           
            //ControlHelper.SetObjectValueToControl(CurrentEntity, panelContent, _isComboBoxSelectValue);
        }

        #endregion

        #region 界面私有方法

        /// <summary>
        /// 取得焦点
        /// </summary>
        /// <param name="containerControl"></param>
        private void GetFocus(Control containerControl)
        {
            foreach (Control eachCtrl in containerControl.Controls)
            {
                // 如果是容器类控件，递归调用                  
                if (eachCtrl.HasChildren)
                {
                    GetFocus(eachCtrl);
                }
                else
                {
                    if (!(eachCtrl is Panel) && eachCtrl.TabIndex == 1)
                    {
                        eachCtrl.Focus();
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 收集界面的值
        /// </summary>
        /// <param name="controlContainer"></param>
        /// <param name="objValueDic"></param>
        /// <param name="isComboBoxSelectValue"></param>
        //private void CollectFormValue(Control controlContainer, Dictionary<string, object> objValueDic, bool isComboBoxSelectValue)
        //{
        //    foreach(Control eachCtrl in controlContainer.Controls)
        //    {
        //        // 如果是容器类控件，递归调用自己                  
        //        if (eachCtrl.HasChildren)
        //        {
        //            CollectFormValue(eachCtrl, objValueDic, isComboBoxSelectValue);
        //        }
        //        else
        //        {
        //            if (eachCtrl is TextBox)
        //            {
        //                TextBox txtBox = eachCtrl as TextBox;

        //                if (!objValueDic.Keys.Contains(txtBox.Name))
        //                    objValueDic.Add(txtBox.Name, txtBox.Text);
        //            }
        //            else if (eachCtrl is System.Windows.Forms.ComboBox)
        //            {
        //                System.Windows.Forms.ComboBox cbb = eachCtrl as System.Windows.Forms.ComboBox;
        //                if (isComboBoxSelectValue)
        //                {
        //                    if (!objValueDic.Keys.Contains(cbb.Name))
        //                        objValueDic.Add(cbb.Name, cbb.SelectedValue);
        //                }
        //                else
        //                {
        //                    if (!objValueDic.Keys.Contains(cbb.Name))
        //                        objValueDic.Add(cbb.Name, cbb.Text);
        //                }
        //            }
        //            else if (eachCtrl is NumericUpDown)
        //            {
        //                NumericUpDown nud = eachCtrl as NumericUpDown;

        //                if (!objValueDic.Keys.Contains(nud.Name))
        //                    objValueDic.Add(nud.Name, nud.Value);
        //            }
        //            else if (eachCtrl is CheckBox)
        //            {
        //                CheckBox ckb = eachCtrl as CheckBox;

        //                if (!objValueDic.Keys.Contains(ckb.Name))
        //                    objValueDic.Add(ckb.Name, ckb.Checked);
        //            }
        //            else if (eachCtrl is DateTimePicker)
        //            {
        //                DateTimePicker dtp = eachCtrl as DateTimePicker;
        //                if (!objValueDic.Keys.Contains(dtp.Name))
        //                    objValueDic.Add(dtp.Name, dtp.Text);
        //            }
        //            else if (eachCtrl is PictureBox)
        //            {
        //                PictureBox picBox = eachCtrl as PictureBox;
        //                if (!objValueDic.Keys.Contains(picBox.Name))
        //                    objValueDic.Add(picBox.Name, picBox.Image);
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 当前是否为view模式
        /// </summary>
        /// <returns></returns>
        private bool IsViewModel()
        {
            if (CurrentOperate == OperationModel.View)
                return true;
            else
                return false;
        }

        #endregion

        #region 点击按钮事件

        #region 增删改操作

        #region 新增操作

        /// <summary>
        /// 点击新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (CurrentOperate == OperationModel.View)
            {
                CurrentOperate = OperationModel.Add;
                
                _currentEntity.ID = string.Empty;
                SetOtherControlEnable(IsViewModel());
            }
            else
            {
                //撤销新增
                CurrentOperate = OperationModel.View;
                SetOtherControlEnable(IsViewModel());
                UndoAdd();
            }
        }

        /// <summary>
        /// 是否允许新增
        /// </summary>
        /// <returns></returns>
        protected virtual bool IsAllowAdd()
        {
            return true;
        }

        protected virtual void UndoAdd()
        {

        }

        /// <summary>
        /// 设置控件默认值
        /// </summary>
        protected virtual void SetDefaultValue()
        {

        }

        #endregion

        #region 删除操作

        /// <summary>
        /// 点击删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteData();
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        protected void DeleteData()
        {
            if (MessageBox.Show("是否删除该记录?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                if (IsAllowDelete())
                {
                    if (Delete() == true)
                    {
                        CurrentOperate = OperationModel.Delete;

                        //操作成功，写日志
                        //LogHelper.WriteLog(_appContext, OperationModel.Delete, OperateContent());

                        lblMsg.Text = "删除成功";
                        AfterDeleted();

                        CurrentOperate = OperationModel.View;
                        SetOtherControlEnable(IsViewModel());
                    }
                }
            }
            else
                return;
        }

        /// <summary>
        /// 判断是否允许删除
        /// </summary>
        /// <returns></returns>
        protected virtual bool IsAllowDelete()
        {
            return true;
        }

        /// <summary>
        /// 删除操作处理
        /// </summary>
        /// <returns></returns>
        protected virtual bool Delete()
        {
            if (panelList.Controls[0] is DataGridView)
            {
                string delSQL = ControlHelper.ConvertToDeleteSQL(_currentEntity.TableName, _currentEntity.ID);
                if (AccessDBHelper.ExecuteSql(delSQL) > 0)
                    return true;
                else
                    return false;
            }

            return true;
        }

        /// <summary>
        /// 删除后处理
        /// </summary>
        protected virtual void AfterDeleted()
        {
            if (panelList.Controls[0] is DataGridView)
            {
                DataGridView dg = panelList.Controls[0] as DataGridView;
                dg.Rows.Remove(dg.SelectedRows[0]);

                if (dg.Rows.Count > 0)
                {
                    dg.Focus();
                    dg.Rows[0].Selected = true;
                }
            }

            return;
        }

        #endregion

        #region 编辑操作

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (CurrentOperate == OperationModel.View)
            {
                if (IsAllowEdit())
                {
                    CurrentOperate = OperationModel.Edit;
                    SetOtherControlEnable(IsViewModel());
                }
            }
            else
            {
                //撤销编辑
                CurrentOperate = OperationModel.View;
                SetOtherControlEnable(IsViewModel());
                //UndoEdit();
            }
        }

        /// <summary>
        /// 是否允许编辑
        /// </summary>
        /// <returns></returns>
        protected virtual bool IsAllowEdit()
        {
            return true;
        }

        #endregion

        #region 保存操作

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValid())
            {
                GetFormValue(_currentEntity);
                if (SaveToDB())
                {
                    SetOtherControlEnable(IsViewModel());
                }
            }
        }

        /// <summary>
        /// 获取窗体内容
        /// </summary>
        protected virtual void GetFormValue(Entity obj)
        {
            if (string.IsNullOrEmpty(obj.ID))
                obj.ID = Guid.NewGuid().ToString("N");

            ControlHelper.SetControlValueToObject(panelContent, obj, _isComboBoxSelectValue);
        }

        /// <summary>
        /// 输入合法性校验
        /// </summary>
        /// <returns>True:输入合法|False:输入非法</returns>
        protected virtual bool IsValid()
        {
            //判断输入是否合法
            return IsInputValid(panelContent);
        }

        /// <summary>
        /// 判断输入是否合法
        /// </summary>
        /// <param name="con"></param>
        /// <returns></returns>
        protected virtual bool IsInputValid(Control ctl)
        {
            return true;
        }

        /// <summary>
        /// 保存数据到数据库
        /// </summary>
        /// <returns></returns>
        private bool SaveToDB()
        {
            try
            {
                if (CurrentOperate == OperationModel.Add)
                {
                    if (InsertIntoDB() == true)
                    {
                        lblMsg.Text = "操作成功!";

                        //操作成功，写日志
                        //LogHelper.WriteLog();

                        CurrentOperate = OperationModel.View;
                        AfterInserted();

                        return true;
                    }
                    else
                    {
                        MessageBox.Show("保存失败，请检查！");
                        return false;
                    }
                }
                else
                {
                    if (UpDateToDB() == true)
                    {
                        lblMsg.Text = "操作成功!";
                        //操作成功，写日志
                        //LogHelper.WriteLog();

                        CurrentOperate = OperationModel.View;
                        AfterUpDated();

                        return true;
                    }
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                //异常日志 TODO
                return false;
            }
        }

        protected virtual bool InsertIntoDB()
        {
            string insertSQL = ControlHelper.ConvertToInsertSQL(_currentEntity.TableName, _currentEntity);

            if (AccessDBHelper.ExecuteSql(insertSQL) > 0)
                return true;
            else
                return false;
        }

        protected virtual bool UpDateToDB()
        {
            string updateSQL = ControlHelper.ConvertToUpdateSQL(_currentEntity.TableName, _currentEntity);

            if (AccessDBHelper.ExecuteSql(updateSQL) > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 新增成功后需要处理的事情(各自画面重写)
        /// </summary>
        protected virtual void AfterInserted()
        {
            WriteDM("UL");
        }

        /// <summary>
        /// 更新成功后需要处理的事情
        /// </summary>
        protected virtual void AfterUpDated()
        {
            WriteDM("UL");
        }

        /// <summary>
        /// 写DM
        /// </summary>
        /// <param name="strType"></param>
        protected virtual void WriteDM(string strType)
        {
        }

        #endregion

        #endregion

        /// <summary>
        /// 点击退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            _appContext.RemoveFormItem(this.Name);
            this.Close();
        }

        #endregion

        #region IClient方法

        //public void chineseVer()
        //{
        //    throw new NotImplementedException();
        //}

        //public void englishVer()
        //{
        //    throw new NotImplementedException();
        //}

        //public void failed(Exception e)
        //{
        //    throw new NotImplementedException();
        //}

        //public void LockScreen()
        //{
        //    throw new NotImplementedException();
        //}

        //public void ReadDM(DM.DmClass obj1)
        //{
        //    throw new NotImplementedException();
        //}

        //public void unlockScreen()
        //{
        //    throw new NotImplementedException();
        //}

        //public void UpdatedPreset(string strRow, string strCol, string strTextValue)
        //{
        //    throw new NotImplementedException();
        //}

        #endregion

        #region 查询按钮事件

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, EventArgs e)
        {
            DataGridView dgv = panelList.Controls[0] as DataGridView;

            if (dgv != null)
            {
                int rowCount = dgv.Rows.Count;
                int cellCount = dgv.Rows[0].Cells.Count;
                string strCondition = this.txtCondition.Text.ToLower();
                bool isExist = false;
                Regex r = new Regex(strCondition);

                //循环行
                for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
                {
                    //循环列
                    for (int cellIndex = 0; cellIndex < cellCount; cellIndex++)
                    {
                        // 在字符串中模糊匹配
                        Match m = r.Match(dgv.Rows[rowIndex].Cells[cellIndex].Value.ToString().ToLower());
                        if (m.Success)
                        {
                            isExist = true;
                            //定位到相同的单元格  
                            if (dgv.Rows[rowIndex].Cells[cellIndex].Visible == true)
                                dgv.CurrentCell = dgv.Rows[rowIndex].Cells[cellIndex];

                            if (MessageBox.Show("是否需要继续查找？", "", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                            {
                                return;
                            }
                        }
                    }
                }

                if (!isExist)
                    MessageBox.Show("您查找的数据不存在!");
            }
        }

        #endregion
    }
}